#pragma once
#include <iostream>
#include <vector>
#include <string>
#include "InetAddr.hpp"
#include <sys/types.h>
#include <sys/socket.h>
#include "ThreadPool.hpp"
#include <functional>
#include"LockGuard.hpp"
using task_t = std::function<void()>;

class MessageRoute
{
private:
    bool IsExist(const InetAddr &addr)
    {
        for (auto a : _online_user)
        {
            if (a == addr)
                return true;
        }
        return false;
    }

public:
    MessageRoute()
    {
        pthread_mutex_init(&_mutex,nullptr);
    }
    void AddUser(const InetAddr &addr)
    {
        LockGuard lockguard(&_mutex);
        if (IsExist(addr))
            return;
        _online_user.push_back(addr);
    }
    void DelUser(const InetAddr &addr)
    {
        LockGuard lockguard(&_mutex);
        for (auto iter = _online_user.begin(); iter != _online_user.end(); iter++)
        {
            if (*iter == addr)
            {
                _online_user.erase(iter);
                break;
            }
        }
    }
    void RouteHelper(int sockfd, std::string message,  InetAddr who)
    {
        LockGuard lockguard(&_mutex);
        for (auto user : _online_user)
        {
           std::string send_message="["+who.IP()+":"+std::to_string(who.Port())+"]# "+message+"\n";
            struct sockaddr_in addr = user.Addr();
            ::sendto(sockfd, message.c_str(), message.size(), 0, (struct sockaddr *)&(addr), sizeof(addr));
        }
    }
    void Route(int sockfd,  std::string message,  InetAddr who)
    {
        AddUser(who);
        if (message == "Q" || message == "QUIT")
        {
            DelUser(who);
        }
        task_t t=std::bind(&MessageRoute::RouteHelper,this,sockfd,message,who);
        ThreadPool <task_t> ::GetInstance()->Enqueue(t);
    }

    ~MessageRoute()
    {
         pthread_mutex_destroy(&_mutex);
    }

private:
    std::vector<InetAddr> _online_user;
    pthread_mutex_t _mutex;
};
